package com.example.wangzh.mytest.part.reingold_tifold;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class BinaryTreeView extends View {
    private TreeNode root; // 根节点
    private Paint nodePaint; // 绘制节点的画笔
    private Paint linePaint; // 绘制连线的画笔
    private Paint textPaint; // 绘制文本的画笔
    private int scale = 100; // 坐标缩放比例

    public BinaryTreeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // 初始化画笔
        nodePaint = new Paint();
        nodePaint.setColor(Color.BLUE);
        nodePaint.setStyle(Paint.Style.FILL);

        linePaint = new Paint();
        linePaint.setColor(Color.BLACK);
        linePaint.setStrokeWidth(4); // 连线宽度
        linePaint.setStyle(Paint.Style.STROKE);

        textPaint = new Paint();
        textPaint.setColor(Color.BLACK); // 文本颜色为黑色
        textPaint.setTextSize(30); // 字体大小
        textPaint.setTextAlign(Paint.Align.CENTER);
    }

    public void setTree(TreeNode root) {
        this.root = root;
        invalidate(); // 刷新视图
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (root != null) {
            // 获取屏幕中心 x 坐标
            int screenCenterX = getWidth() / 2;
            drawTree(canvas, root, screenCenterX);
        }
    }

    private void drawTree(Canvas canvas, TreeNode node, int screenCenterX) {
        if (node == null) {
            return;
        }

        // 将整数坐标映射到屏幕的实际像素坐标，并相对于屏幕中心调整 x 坐标
        int screenX = screenCenterX + node.x * scale;
        int screenY = node.y * scale;

        // 绘制当前节点
        canvas.drawCircle(screenX, screenY, 30, nodePaint);

        // 绘制节点值
        canvas.drawText(String.valueOf(node.value), screenX, screenY + 10, textPaint);

        // 绘制节点坐标
        String coordinate = "(" + node.x + ", " + node.y + ")";
        canvas.drawText(coordinate, screenX, screenY + 50, textPaint);

        // 绘制左子节点连线
        if (node.left != null) {
            int leftScreenX = screenCenterX + node.left.x * scale;
            int leftScreenY = node.left.y * scale;
            Path path = new Path();
            path.moveTo(screenX, screenY);
            path.lineTo(leftScreenX, leftScreenY);
            canvas.drawPath(path, linePaint);
            drawTree(canvas, node.left, screenCenterX);
        }

        // 绘制右子节点连线
        if (node.right != null) {
            int rightScreenX = screenCenterX + node.right.x * scale;
            int rightScreenY = node.right.y * scale;
            Path path = new Path();
            path.moveTo(screenX, screenY);
            path.lineTo(rightScreenX, rightScreenY);
            canvas.drawPath(path, linePaint);
            drawTree(canvas, node.right, screenCenterX);
        }
    }
}
